<?php
declare (strict_types=1);

namespace app\admin\logic\content\agreement;

use app\admin\logic\system\Log;
use app\admin\model\content\agreement\Agreement as AgreementModel;
use app\common\exception\LogicException;

/**
 * 协议逻辑层
 */
class Agreement extends AgreementModel
{
    /**
     * 获取列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-04
     *
     * @return   [type]                         [description]
     */
    public function getList(array $map = [])
    {
        return $this->with(['lastActionUser'])->where($map)->order('update_time', 'DESC')->paginate($this->getListRows());
    }

    /**
     * 创建
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-04
     *
     * @param array $data [description]
     * @return   [type]                               [description]
     */
    public function createAgreement(array $data)
    {

        // 验证数据
        $this->getValidate()->scene('create')->failException()->check($data);

        $save = [
            'key'       => $data['key'],
            'title'     => $data['title'],
            'content'   => $data['content'],
            'remark'    => $data['remark'] ?? '',
            'is_system' => 0// $data['is_system'] == 1 ? 1 : 0,
        ];

        // 创建成功
        if (!$this->save($save)) {
            throw new LogicException('创建失败');
        }

        Log::write('新建协议【' . $data['title'] . '】', 'content_agreement', 'create', true);

        // 返回值
        return $this;
    }

    /**
     * 编辑
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-04
     *
     * @param    [type]                         $id   [description]
     * @param    [type]                         $data [description]
     * @return   [type]                               [description]
     */
    public function editAgreement($id, $data)
    {
        $agreement = $this->where('id', $id)->findOrFail();

        $check       = $data;
        $check['id'] = $id;
        // 验证数据
        $this->getValidate()->scene('edit')->failException()->check($check);

        $agreement->key       = $data['key'];
        $agreement->title     = $data['title'];
        $agreement->content   = $data['content'];
        $agreement->remark    = $data['remark'];
        $agreement->is_system = 0;// $data['is_system'] == 1 ? 1 : 0;

        if (!$agreement->save()) {
            throw new LogicException('修改失败');
        }

        Log::write('编辑协议【' . $data['title'] . '】', 'content_agreement', 'update', true);

        return $agreement;
    }

    /**
     * 删除
     * Author   Martinsun<syh@sunyonghong.com>
     * Date: 2020-06-04
     *
     * @param    [type]                         $id [description]
     * @return   [type]                             [description]
     */
    public function deleteAgreement($id)
    {
        $agreement = $this->where('id', $id)->where('is_system', 0)->findOrFail();

        if (!$agreement->delete()) {
            throw new LogicException("删除失败");
        }

        Log::write('删除协议【' . $agreement->title . '】', 'content_agreement', 'delete', true);
    }

    /**
     * 搜索协议
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-05
     *
     * @param string $keyword [description]
     * @return   [type]                                  [description]
     */
    public function getSearchList(string $keyword = '')
    {
        return $this->where(function ($query) use ($keyword) {
            $query->where('key', 'like', '%' . $keyword . '%')->whereOr('title', 'like', '%' . $keyword . '%');
        })->field(['key' => 'value', 'title', 'id'])->limit(10)->select();
    }

    /**
     * 获取机构的选项key
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/7/2
     *
     * @return array
     */
    public function getAgreementKeyOptions()
    {
        // 获取机构已经添加的协议
        $keys     = $this->column('key');
        $keysList = $this->getAgreementKeysList();
        $options  = [];
        foreach ($keysList as $item) {
            if (!in_array($item['key'], $keys)) {
                if (request()->is_platform && in_array($item['type'], [1, 2])) {
                    // 1和2
                    $options[] = [
                        'title' => $item['title'],
                        'value' => $item['key']
                    ];
                } else if (in_array($item['type'], [1, 3])) {
                    // 1和3
                    $options[] = [
                        'title' => $item['title'],
                        'value' => $item['key']
                    ];
                }

            }
        }

        return $options;
    }

    /**
     * 根据key获取协议类型标题
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/7/5
     *
     * @param string $key
     * @return mixed|string
     */
    public function getAgreementTitleByKey(string $key)
    {
        $keys = $this->getAgreementKeysList();
        $keys = array_column($keys, 'title', 'key');

        return $keys[$key] ?? '';
    }

    /**
     * 获取协议类容
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/7/5
     *
     * @param string $key
     * @return mixed
     */
    public function getContentByKey(string $key, $mhmId = 1)
    {
        return $this->withoutGlobalScope(['mhm'])->where('mhm_id', $mhmId)->where('key', $key)->value('content');
    }
}
